package org.example.commond.handler.room;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.example.commond.AbstractCmdHandler;
import org.example.commond.CommandManager;
import org.example.component.UserInfo;
import org.example.config.Im;
import org.example.config.ImConfig;
import org.example.enums.CommandEnum;
import org.example.listener.ImGroupPropListener;
import org.example.packets.bean.Group;
import org.example.packets.bean.User;
import org.example.packets.handler.message.ChatReqBody;
import org.example.packets.handler.system.RespBody;
import org.example.packets.handler.room.GroupProfileReqBody;
import org.example.util.JsonUtil;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

public class EditGroupProfileReqHandler extends AbstractCmdHandler {

    @Override
    public CommandEnum command() {
        return CommandEnum.COMMAND_EDIT_GROUP_PROFILE_REQ;
    }

    @Override
    public WsResponse handler(Packet packet, ChannelContext channelContext) {

        GroupProfileReqBody body = JsonUtil.format(packet, GroupProfileReqBody.class);

        Group group = BeanUtil.copyProperties(body, Group.class);

        ImConfig.groupPropListener().onPropChange(group);


        WsResponse response = WsResponse.fromText(RespBody.success(CommandEnum.COMMAND_EDIT_GROUP_PROFILE_RESP, body), Im.CHARSET);
        Im.sendToGroup(body.getRoomId(), response);

        // 发送修改信息
        User nowUser = UserInfo.user();
        AbstractCmdHandler command = CommandManager.getCommand(CommandEnum.COMMAND_CHAT_REQ);
        if (StrUtil.isNotBlank(body.getRoomName())) {
            ChatReqBody chatReqBody = ChatReqBody.buildSystem(body.getRoomId(), nowUser.getId(), nowUser.getUsername() + "修改了群名称");
            WsRequest wsRequest = WsRequest.fromText(JSON.toJSONString(chatReqBody, SerializerFeature.DisableCircularReferenceDetect), Im.CHARSET);
            command.handler(wsRequest, channelContext);
        }
        if (StrUtil.isNotBlank(body.getAvatar())) {
            ChatReqBody chatReqBody = ChatReqBody.buildSystem(body.getRoomId(), nowUser.getId(), nowUser.getUsername() + "修改了群头像");
            WsRequest wsRequest = WsRequest.fromText(JSON.toJSONString(chatReqBody, SerializerFeature.DisableCircularReferenceDetect), Im.CHARSET);
            command.handler(wsRequest, channelContext);
        }

        return null;
    }
}
